997. 找到小镇的法官

997. 找到小镇的法官

方案

法官没有出度, 且法官入度等于 N - 1

遍历查询出度与入度。满足入度为 N-1 且出度为 0 者即为所求。

var findJudge = function (N, trust) {
    const adjList = {}
    // base 是 1
    const trustCount = new Array(N + 1).fill(0)
    for (const t of trust) {
        // t[0]信任t[1]
        if (!adjList.hasOwnProperty(t[0])) adjList[t[0]] = []
        adjList[t[0]].push(t[1])
        trustCount[t[1]]++
    }
    // 遍历邻接表,找到没有出度的,判断入度是否为N-1
    for (let i = 1; i <= N; i++) {
        if (!adjList.hasOwnProperty(i) && trustCount[i] === N - 1) return i
    }
    return -1
}
let N = 2, trust = [[1, 2]]
console.log(findJudge(N, trust))